package com.eightbears.beboy.ui.user.fragment;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.eightbears.beboy.R;
import com.eightbears.beboy.base.BaseFragment;
import com.eightbears.beboy.base.util.CommonUtils;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.BlurringView;
import com.eightbears.beboy.base.view.dialog.AddCodeDialog;
import com.eightbears.beboy.base.view.qrcode.utils.CodeUtils;
import com.eightbears.beboy.entity.StaticDataEntity;
import com.eightbears.beboy.entity.UserEntity;
import com.eightbears.beboy.entity.UserInfoEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.eightbears.beboy.ui.user.activity.ByVipActivity;
import com.eightbears.beboy.ui.user.activity.FocusShopActivity;
import com.eightbears.beboy.ui.user.activity.GrowLevelActivity;
import com.eightbears.beboy.ui.user.activity.MyClientActivity;
import com.eightbears.beboy.ui.user.activity.MyDynamicActivity;
import com.eightbears.beboy.ui.user.activity.MyPostActivity;
import com.eightbears.beboy.ui.user.activity.MyWalletActivity;
import com.eightbears.beboy.ui.user.activity.OrderListActivity;
import com.eightbears.beboy.ui.user.activity.RedActivity;
import com.eightbears.beboy.ui.user.activity.SetMealOrderActivity;
import com.eightbears.beboy.ui.user.activity.SettingActivity;
import com.eightbears.beboy.ui.user.activity.ShopActivity;
import com.eightbears.beboy.ui.user.activity.TakeMoneyActivity;
import com.eightbears.beboy.ui.user.activity.UserPublishInfo;
import com.makeramen.roundedimageview.RoundedImageView;
import com.socks.library.KLog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.PARAMS_USER_ID;
import static com.eightbears.beboy.base.util.CommonAPI.URL_RESET_USERDATA;
import static com.eightbears.beboy.ui.user.activity.PaymentActivity.EVENT_MY_PAY;
import static com.eightbears.beboy.ui.user.activity.SettingActivity.EVENT_USER_HEAD_UPDATE;

public class MyFragment extends BaseFragment {

    public static final String EVENT_UPDATE_USERINFO = "userinfo";


    @BindView(R.id.iv_head_bg)
    ImageView mIvHeadBg;
    @BindView(R.id.blurring_view)
    BlurringView mBlurring_view;
    @BindView(R.id.iv_head)
    RoundedImageView mIvHead;
    @BindView(R.id.iv_sex)
    ImageView mIv_sex;
    @BindView(R.id.iv_level)
    ImageView mIv_level;
    @BindView(R.id.tv_sex)
    TextView mTvSex;
    @BindView(R.id.tv_nickname)
    TextView mTvNickname;
    @BindView(R.id.activity_user_publish_info)
    LinearLayout mActivityUserPublishInfo;
    @BindView(R.id.ll_set)
    LinearLayout mLl_set;
    @BindView(R.id.ll_fan)
    LinearLayout mLlFan;
    @BindView(R.id.ll_theme)
    LinearLayout mLlTheme;
    @BindView(R.id.rl_user_publish_info)
    RelativeLayout mRlUserPublishInfo;
    @BindView(R.id.rl_red)
    RelativeLayout mRlRed;
    @BindView(R.id.rl_my_set_meal)
    RelativeLayout mRlMySetMeal;
    @BindView(R.id.rl_my_book)
    RelativeLayout mRlMyBook;
    @BindView(R.id.rl_my_buy)
    RelativeLayout mRlMyBuy;
    @BindView(R.id.rl_vip)
    RelativeLayout mRlVip;
    @BindView(R.id.rl_money)
    RelativeLayout mRl_money;
    @BindView(R.id.rl_shop)
    RelativeLayout mRlShop;
    @BindView(R.id.tv_balance)
    TextView tv_balance;
    @BindView(R.id.iv_vip)
    ImageView iv_vip;
    @BindView(R.id.tv_posts)
    TextView tv_posts;
    @BindView(R.id.tv_fav)
    TextView tv_fav;

    private UserEntity mUserEntity;
    private AddCodeDialog.Builder mBuilder;
    private Bitmap mBitmapCover;
    private String mBalance;
    private UserInfoEntity mUserInfoEntity;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_my, container, false);
        ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        initView();
        initData();
        initEvent();
        return view;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void initView() {
        mUserEntity = SPUtil.getUser();
        StaticDataEntity staticData = SPUtil.getStaticData();
        mTvNickname.setText(mUserEntity.getData().getNickname());
        CommonUtils.loadImageView(getActivity(), mUserEntity.getData().getCover(), R.mipmap.default_head, mIvHead);
        Glide.with(getActivity()).load(mUserEntity.getData().getCover()).asBitmap().into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                mBitmapCover = resource;
            }
        });

        if (staticData != null) {
            if (staticData.getData().getActivity().getI_want_cash().getFlag() == 1) {
                mRl_money.setVisibility(View.VISIBLE);
            }
        }

        if (TextUtils.isEmpty(mUserEntity.getData().getSex())) {
            mIv_sex.setVisibility(View.GONE);

        } else if (mUserEntity.getData().getSex().equals(getString(R.string.text_man))) {
            mIv_sex.setImageDrawable(getActivity().getDrawable(R.mipmap.icon_male));
            mTvSex.setText(mUserEntity.getData().getSex());

        } else if (mUserEntity.getData().getSex().equals(getString(R.string.text_women))) {
            mIv_sex.setImageDrawable(getActivity().getDrawable(R.mipmap.icon_female));
            mTvSex.setText(mUserEntity.getData().getSex());
        }

        if (mUserEntity.getData().getVip_level() == 1) {
            iv_vip.setVisibility(View.VISIBLE);
            iv_vip.setImageResource(R.mipmap.icon_new_vip1);
        } else if (mUserEntity.getData().getVip_level() == 2) {
            iv_vip.setVisibility(View.VISIBLE);
            iv_vip.setImageResource(R.mipmap.icon_new_vip2);
        } else {
            iv_vip.setVisibility(View.GONE);
        }

        if (mUserEntity.getData().getPoints() != null) {
            if (mUserEntity.getData().getPoints().getLevel() == 1) {
                mIv_level.setImageResource(R.mipmap.icon_level_one);
            } else if (mUserEntity.getData().getPoints().getLevel() == 2) {
                mIv_level.setImageResource(R.mipmap.icon_level_two);
            } else if (mUserEntity.getData().getPoints().getLevel() == 3) {
                mIv_level.setImageResource(R.mipmap.icon_level_three);
            } else if (mUserEntity.getData().getPoints().getLevel() == 4) {
                mIv_level.setImageResource(R.mipmap.icon_level_four);
            } else if (mUserEntity.getData().getPoints().getLevel() == 5) {
                mIv_level.setImageResource(R.mipmap.icon_level_five);
            }
            mIv_level.setVisibility(View.VISIBLE);
        }

        tv_balance.setText(mUserEntity.getData().getBalance());
        mBlurring_view.setBlurredView(mIvHeadBg);
        mBlurring_view.invalidate();
    }

    @Override
    protected void initData() {
        getUserinfo();
    }


    @Override
    protected void initEvent() {


    }


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void showHead() {
        UserEntity user = SPUtil.getUser();
        CommonUtils.loadImageView(getActivity(), user.getData().getCover(), R.mipmap.default_head, mIvHead);
        KLog.e("showHead " + user.getData().getCover());

        Glide.with(getActivity()).load(user.getData().getCover()).asBitmap().into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                mBitmapCover = resource;
            }
        });

        mTvNickname.setText(user.getData().getNickname());
        KLog.e((user.getData().getSex()));
        if (TextUtils.isEmpty(user.getData().getSex())) {
            mIv_sex.setVisibility(View.GONE);
        } else if (user.getData().getSex().equals("1")) {
            mIv_sex.setImageDrawable(getActivity().getDrawable(R.mipmap.icon_male));
            mTvSex.setText(user.getData().getSex());
            mTvSex.setText(getString(R.string.text_man));
            KLog.e("男");
        } else if (user.getData().getSex().equals("2")) {
            mIv_sex.setImageDrawable(getActivity().getDrawable(R.mipmap.icon_female));
            mTvSex.setText(user.getData().getSex());
            mTvSex.setText(getString(R.string.text_women));
            KLog.e("女");
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDataSynEvent(String event) {
        switch (event) {
            case EVENT_USER_HEAD_UPDATE:
                showHead();
                break;
            case EVENT_UPDATE_USERINFO:
                showHead();
                break;
            case EVENT_MY_PAY:
                getUserinfo();
                break;
        }
    }

    @OnClick({R.id.iv_head_bg, R.id.iv_share, R.id.rl_level, R.id.rl_money, R.id.rl_popularize, R.id.iv_head, R.id.ll_set, R.id.activity_user_publish_info, R.id.ll_balance, R.id.ll_fan, R.id.ll_theme, R.id.rl_user_publish_info, R.id.rl_red, R.id.rl_my_set_meal, R.id.rl_my_book, R.id.rl_my_buy, R.id.rl_vip, R.id.rl_shop})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_head_bg:
                break;
            case R.id.rl_level:
                startLocalActivity(GrowLevelActivity.class);
                break;
            case R.id.rl_money:
                startLocalActivity(TakeMoneyActivity.class);
                break;
            case R.id.iv_share:
                String friend = "beboy://friend/" + mUserEntity.getData().getUser_id();
                if (null == mBuilder) {
                    mBuilder = new AddCodeDialog.Builder(getActivity());
                    if (mBitmapCover != null) {
                        mBuilder.setBitmap(CodeUtils.createImage(friend, 150, 150, CommonUtils.bg2WhiteBitmap(mBitmapCover)));
                    } else {
                        mBuilder.setBitmap(CodeUtils.createImage(friend, 150, 150, CommonUtils.bg2WhiteBitmap(BitmapFactory.decodeResource(getActivity().getResources(), R.mipmap.default_head))));
                    }
                }
                mBuilder.create().show();
                break;
            case R.id.iv_head:
                startLocalActivity(SettingActivity.class);
                break;
            case R.id.ll_set:
                startLocalActivity(SettingActivity.class);
                break;
            case R.id.activity_user_publish_info:
                break;
            case R.id.ll_balance:
                startLocalActivity(MyWalletActivity.class, EVENT_UPDATE_USERINFO, mUserInfoEntity);
                break;
            case R.id.ll_fan:
                startLocalActivity(FocusShopActivity.class);
                break;
            case R.id.ll_theme:
                startLocalActivity(UserPublishInfo.class, PARAMS_USER_ID, mUserEntity.getData().getUser_id());
//                startLocalActivity(LeftMenuCollectActivity.class);
                break;
            case R.id.rl_user_publish_info:
                startLocalActivity(MyDynamicActivity.class);
                break;
            case R.id.rl_red:
                startLocalActivity(RedActivity.class);
                break;
            case R.id.rl_my_set_meal:
                startLocalActivity(SetMealOrderActivity.class);
                break;
            case R.id.rl_my_book:
                startLocalActivity(OrderListActivity.class);
                break;
            case R.id.rl_my_buy:
                startLocalActivity(MyPostActivity.class);
                break;
            case R.id.rl_vip:
                startLocalActivity(ByVipActivity.class);
                break;
            case R.id.rl_shop:
                startLocalActivity(ShopActivity.class, EVENT_UPDATE_USERINFO, mUserInfoEntity);
                break;
            case R.id.rl_popularize:
                startLocalActivity(MyClientActivity.class, EVENT_UPDATE_USERINFO, mUserInfoEntity);
                break;
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            //刷新数据
            updateData();
        }
    }

    private void updateData() {
        getUserinfo();
    }

    /**
     * 获取用户数据
     */
    public void getUserinfo() {
        //获取token
        OkHttpUtils.get().url(URL_RESET_USERDATA + mUserEntity.getData().getUser_id())
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("need_withdraw_config", "1")
                .build().execute(new StringCallback() {

            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onResponse(String response) {
                UserEntity userEntity = GsonUtil.fromJson(response, UserEntity.class);
                userEntity.getData().setAccess_token(mUserEntity.getData().getAccess_token());
                SPUtil.putUser(userEntity);
                mUserInfoEntity = GsonUtil.fromJson(response, UserInfoEntity.class);
                if (CONNECTION_STATUS_SUCCESS.equals(mUserInfoEntity.getStatus_code())) {
                    tv_fav.setText(mUserInfoEntity.getData().getShop_fav());
                    tv_posts.setText(mUserInfoEntity.getData().getPosts());
                    mTvNickname.setText(mUserInfoEntity.getData().getNickname());
                    if (TextUtils.isEmpty(mUserInfoEntity.getData().getSex())) {
                        mIv_sex.setVisibility(View.GONE);
                    } else if (mUserInfoEntity.getData().getSex().equals(getActivity().getString(R.string.text_man))) {
                        mIv_sex.setImageDrawable(getActivity().getDrawable(R.mipmap.icon_male));
                        mTvSex.setText(mUserInfoEntity.getData().getSex());
                    } else if (mUserInfoEntity.getData().getSex().equals(getString(R.string.text_women))) {
                        mIv_sex.setImageDrawable(getActivity().getDrawable(R.mipmap.icon_female));
                        mTvSex.setText(mUserInfoEntity.getData().getSex());
                    }
                    if (mUserInfoEntity.getData().getVip_level() > 0) {
                        iv_vip.setVisibility(View.VISIBLE);
                    } else {
                        iv_vip.setVisibility(View.GONE);
                    }
                    mBalance = mUserInfoEntity.getData().getBalance();
                    tv_balance.setText(mBalance);
                    KLog.e("" + userEntity.getData().getCover());
                    CommonUtils.loadImageView(getActivity(), userEntity.getData().getCover(), R.mipmap.default_head, mIvHead);
                    Glide.with(getActivity()).load(userEntity.getData().getCover()).asBitmap().into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                            mBitmapCover = resource;
                        }
                    });
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                KLog.e(e.getMessage());
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(getActivity(), status_error);
            }
        });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
